<template>
    <BaseParam :label="label" :help="help">
        <div class="image-param">
            <el-upload
                class="image-uploader"
                :action="null"
                :auto-upload="false"
                :show-file-list="false"
                accept="image/*"
                @change="handleImageChange"
            >
                <img v-if="imageUrl" :src="imageUrl" class="preview-image" />
                <el-icon v-else class="upload-icon"><Plus /></el-icon>
            </el-upload>
            <div v-if="config?.description" class="param-description">
                {{ config.description }}
            </div>
        </div>
    </BaseParam>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import BaseParam from './BaseParam.vue';
import type { ParamConfig } from './types';

const props = defineProps<{
    modelValue?: string;
    label: string;
    help?: string;
    config?: {
        description?: string;
        maxSize?: number;
        aspectRatio?: number;
    };
}>();

const emit = defineEmits<{
    (e: 'update:modelValue', value: string): void;
}>();

const imageUrl = ref(props.modelValue || '');

watch(() => props.modelValue, (newValue) => {
    imageUrl.value = newValue || '';
});

const handleImageChange = (file: File) => {
    const reader = new FileReader();
    reader.onload = (e) => {
        const dataUrl = e.target?.result as string;
        imageUrl.value = dataUrl;
        emit('update:modelValue', dataUrl);
    };
    reader.readAsDataURL(file.raw);
};
</script>

<style lang="scss" scoped>
.image-param {
    .image-uploader {
        :deep(.el-upload) {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: border-color 0.3s;

            &:hover {
                border-color: #409eff;
            }
        }

        .upload-icon {
            font-size: 28px;
            color: #8c939d;
            width: 120px;
            height: 120px;
            line-height: 120px;
            text-align: center;
        }

        .preview-image {
            width: 120px;
            height: 120px;
            display: block;
            object-fit: cover;
        }
    }

    .param-description {
        font-size: 12px;
        color: #909399;
        margin-top: 8px;
    }
}
</style> 